import { Module } from "@nestjs/common";
import { TypeOrmConfigService } from './typeorm-config.service';
import { TypeOrmModule, TypeOrmModuleAsyncOptions } from '@nestjs/typeorm';
import { DataSource } from 'typeorm';
import { ConfigService } from "@nestjs/config";
import { AppService } from "@/app.service";
import { User } from "@/examples/user/entities/user.entity";
import { TypeOrmProvider } from "./typeorm.provider";
import { TYPEORM_DATABASE } from "../database.constants";
import { TypeOrmRepository } from "@/examples/user/repositories/typeorm.repository";

const connections = new Map()

@Module({
    imports: [
        // TypeOrmModule.forRoot({
        //   name: "mysql1",
        //   type: "mysql", //数据库类型
        //   username: "root", //账号
        //   password: "123456", //密码
        //   host: "localhost", //host
        //   port: 3306, //端口
        //   database: "nest_demo", //库名
        //   entities: [__dirname + '/**/*.entity{.ts,.js}'], //实体文件
        //   synchronize: true, //synchronize字段代表是否自动将实体类同步到数据库
        //   retryDelay: 500, //重试连接数据库间隔
        //   retryAttempts: 10,//重试连接数据库的次数
        //   autoLoadEntities: true, //如果为true,将自动加载实体 forFeature()方法注册的每个实体都将自动添加到配置对象的实体数组中
        //   poolSize: 10, // 最大连接池
        // }),
        // TypeOrmModule.forRootAsync({
        //     name: 'mysql2',
        //     inject: [ConfigService, AppService],
        //     extraProviders: [AppService],
        //     useFactory: (configService: ConfigService, appService: AppService) => {
        //         const config = appService.getDBConfig();
        //         const envConfig = {
        //             type: configService.get('DB_TYPE'),
        //             username: configService.get('DB_USERNAME'),
        //             password: configService.get('DB_PASSWORD'),
        //             host: configService.get('DB_HOST'),
        //             port: configService.get('DB_PORT'),
        //             database: configService.get('DB_DATABASE'),
        //             entities: [__dirname + '/**/*.entity{.ts,.js}'],
        //             synchronize: Boolean(configService.get('DB_SYNC')),
        //             retryDelay: 500,
        //             retryAttempts: 10,
        //             autoLoadEntities: Boolean(configService.get('DB_AUTOLOAD')),
        //             poolSize: 5,
        //         }
        //         const finialConfig = { ...envConfig, ...config }
        //         return finialConfig as TypeOrmModuleAsyncOptions
        //     }
        // }),
        TypeOrmModule.forRootAsync({
            name: TYPEORM_DATABASE,
            useClass: TypeOrmConfigService,
            // 自定义TypeOrm数据源异步配置，用于解决多数据库连接池太多导致内存过大问题
            dataSourceFactory: async (options: any) => {
                // tanantId
                const tanantId = options['tanantId'] || 'default'
                if (tanantId && connections.has(tanantId)) {
                    return connections.get(tanantId)
                }
                const dataSource = await new DataSource(options).initialize()
                connections.set(tanantId, dataSource)
                return dataSource
            },
            inject: [],
            extraProviders: [],
        }),
        TypeOrmModule.forFeature([User], TYPEORM_DATABASE), // 关联实体
    ],
    providers: [
        TypeOrmProvider,
        {
            provide: 'TYPEORM_CONNECTIONS',
            useValue: connections
        },
        TypeOrmRepository
    ],
    exports: [TypeOrmRepository]
})
export class TypeOrmCommonModule {

}